package com.profound.notes.main.slice;

import com.profound.notes.ResourceTable;
import com.profound.notes.main.slice.m.NoteModel;
import com.profound.notes.main.slice.vm.NoteViewModel;
import com.profound.notes.mvvm.Observer;
import com.profound.notes.mvvm.ViewModelProvider;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.*;

import java.util.List;

/**
 * @author zjwujlei
 * @date 2021/4/24
 * @email zjwujlei@sina.com
 * @description
 */
public class NoteItemProvider extends BaseItemProvider {

    private NoteViewModel vm;
    private List<NoteModel> notes;
    private AbilitySlice slice;

    public NoteItemProvider(ViewModelProvider provider, AbilitySlice slice){
        vm = provider.get(NoteViewModel.class);
        this.slice = slice;
        notes =vm.notes.getValue();
        vm.notes.observe(slice, new Observer<List<NoteModel>>() {
            @Override
            public void onChanged(List<NoteModel> noteModels) {
                notes =vm.notes.getValue();
                notifyDataInvalidated();
            }
        });
    }

    @Override
    public int getCount() {
        return notes.size();
    }

    @Override
    public Object getItem(int i) {
        return notes.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        final NoteModel model = notes.get(i);
        if (component == null){
            component = LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_main_note_page_item,componentContainer,false);
        }
        Text context = (Text) component.findComponentById(ResourceTable.Id_main_note_page_item_context);
        Text time = (Text) component.findComponentById(ResourceTable.Id_main_note_page_item_time);
        context.setText(model.content);
        time.setText(model.modifyTime);
        return component;
    }
}
